package com.zxbit.uangstore.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

public class PackageUtils {
    public static List<AppInfo> getAllApps(Context context) {

        List<AppInfo> apps = new ArrayList<AppInfo>();
        PackageManager pManager = context.getPackageManager();
        // 获取手机内所有应用
        List<PackageInfo> packlist = pManager.getInstalledPackages(0);
        for (int i = 0; i < packlist.size(); i++) {
            PackageInfo pak = (PackageInfo) packlist.get(i);

            // 判断是否为非系统预装的应用程序
            // 这里还可以添加系统自带的，这里就先不添加了，如果有需要可以自己添加
            // if()里的值如果<=0则为自己装的程序，否则为系统工程自带
            if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
                // 添加自己已经安装的应用程序
                AppInfo info = new AppInfo();
                info.setAppName(pak.applicationInfo.loadLabel(pManager).toString());
                info.setAppApkName(pak.packageName);
                apps.add(info);
            }

        }
        return apps;
    }

    public static boolean isInstall(Context context, String packageName) {
        List<PackageUtils.AppInfo> appInfoList = PackageUtils.getAllApps(context);
        for (int i = 0; i < appInfoList.size(); i++) {
            if (packageName.equals(appInfoList.get(i).getAppApkName())) {
                return true;
            }
        }
        return false;
    }

    public static class AppInfo {
        private String appName;

        public String getAppApkName() {
            return appApkName;
        }

        public void setAppApkName(String appApkName) {
            this.appApkName = appApkName;
        }

        private String appApkName;

        public String getAppName() {
            return appName;
        }

        public void setAppName(String appName) {
            this.appName = appName;
        }

    }

    public static boolean checkApkExist(Context context, String packageName){
        if (TextUtils.isEmpty(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }
}
